from app.helpers.csv_import import UnicodeReader
from app.models.artist import Artist
from app.models.song import Song
from google.appengine.ext import webapp
import datetime
import logging


class ImportDataPage(webapp.RequestHandler):
    def get(self, *args):
        reader = UnicodeReader(open("/home/marjan/workspace/HelloWorld/loaders/artist_data.csv", "rb"), delimiter=';', quotechar='"')
        #header
        reader.next();
        for line in reader:
            artist = Artist()
            artist.code = int(line[0])
            artist.name = line[1]
            artist.image = line[2]
            artist.description = line[3]
            artist.date = datetime.datetime.combine(datetime.datetime.strptime(line[4].strip(), '%d.%m.%Y').date(), datetime.time())
            logging.error("0" + artist.description)
            artist.save();
            logging.error("1" + artist.description)
            artist = Artist.get_by_code(artist.code)
            logging.error("2" + artist.description)
        self.response.out.write("ok")
        
        reader = UnicodeReader(open("/home/marjan/workspace/HelloWorld/loaders/song_data.csv", "rb"))
        for line in reader:
            song = Song()
            song.name = line[0]
            song.description = line[1]
            song.date = datetime.datetime.combine(datetime.datetime.strptime(line[2].strip(), '%d.%m.%Y').date(), datetime.time())
            logging.error(int(line[3].strip()))
            songArtist = Artist.gql("where code = :code", code = int(line[3].strip())).get()
            song.artist = songArtist
            song.save();
        self.response.out.write("ok")
